import math

from django.core.paginator import Paginator
from django.http import JsonResponse
from NoFish import debug
from article.models import Article
from love.models import Love


# 分页器
def pageData(page_index, uid):
    allData = Article.objects.filter(article1__lover_id=uid).order_by("-createTime")
    allpage = math.ceil(allData.count() / 5)
    paginator = Paginator(allData, 5)  # 每页5条
    return paginator.get_page(page_index), allpage


# 处理点赞的文章
def loveList(datas, pageNum, uid):
    try:
        articles = []
        for d in datas:
            t = {
                'art_id': d.aid,  # 文章id
                'nickname': d.user.nickname,
                "uimg":d.user.img.url,
                'img': d.img.url,
                'title': d.title,
                'content': d.content,
                'createTime': d.createTime,
                'loveNum': d.article1.count(),
                "zhaiyao": d.zhaiyao,
                "statu": d.statu,  # 文章状态
                "islove": Love.objects.filter(lover_id=uid, art_id=d.aid).exists(),
            }
            articles.append(t)
        return JsonResponse({"statu": True, "articles": articles, "pageNum": pageNum})
    except Exception as e:
        debug.writeBug(e)
        print("love=>view=>loveList", e)
        return JsonResponse({'statu': False})


# 查询用户点赞的文章
def find_love(request, index, uid):
    datas = pageData(index, uid)
    return loveList(datas[0], datas[1], uid)


# 点赞状态
def add_love(request):
    try:
        # 点赞
        aid = request.GET.get("aid")
        uid = request.GET.get("uid")
        love = Love.objects.filter(lover_id=uid, art_id=aid)
        # 如果不存在则添加
        if not love.exists():
            print("add...")
            love = Love(
                lover_id=uid,
                art_id=aid
            )
            love.save()
            article = Article.objects.filter(aid=aid).first()
            article.save()  # 文章点赞加一
        return JsonResponse({"statu": True})
    except Exception as e:
        print("addLove error ", e)
        return JsonResponse({"statu": False, "reason": "后台故障，请联系管理人员"})

# 取消点赞
def unadd_love(request):
    try:
        # 取消点赞
        aid = request.GET.get("aid")
        uid = request.GET.get("uid")
        love = Love.objects.filter(lover_id=uid,art_id=aid)
        # 如果文章存在的话
        if love.exists():
            print("unadd...")
            love.first().delete()
            article = Article.objects.filter(aid=aid).first()
            article.save()  # 文章点赞减一
        return JsonResponse({"statu": True})
    except Exception as e:
        print("UnaddLove error ", e)
        return JsonResponse({"statu": False, "reason": "后台故障，请联系管理人员"})